package com.saint.commons.service;

import com.alibaba.csp.sentinel.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.VariableInstanceEntity;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class ActivityService {
    private final ProcessEngine processEngine;
//    private final ProcessEngine processEngineByConfig;

    public void commit(String type) {
        long start = System.currentTimeMillis();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        log.info(String.valueOf(processEngine));
        log.info("init commit - {}", System.currentTimeMillis() - start);
        //进行部署
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("bpmn/1.bpmn")
                .addClasspathResource("bpmn/1.bpmn.png")
                .name("报销流程")
                .deploy();
        //输出部署的一些信息
        log.info("流程部署ID:{}", deployment.getId());

        /*repositoryService.createDeployment()
                .name("expense-process.bar")
                .addClasspathResource("org/activiti/expenseProcess.bpmn20.xml")
                .addClasspathResource("org/activiti/expenseProcess.png")
                .deploy();*/

        TaskService taskService = processEngine.getTaskService();
        ManagementService managementService = processEngine.getManagementService();

        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee("zhangsan")
//                .processVariableValueEquals("orderId", "0815")
                .orderByTaskDueDate()
                .asc()
                .list();
        log.info("tasks : {}", tasks);
        for (Task task : tasks) {
            log.info("task : {}", task);
        }

        List<Task> tasks2 = taskService.createNativeTaskQuery()
                .sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T WHERE T.NAME_ = #{taskName}")
                .parameter("taskName", "zhangsan")
                .list();
        log.info("tasks2 : {}", tasks2);
        for (Task task : tasks2) {
            log.info("task2 : {}", task);
        }
        long count = taskService.createNativeTaskQuery()
                .sql("SELECT count(*) FROM " + managementService.getTableName(Task.class) + " T1, "
                        + managementService.getTableName(VariableInstanceEntity.class) + " V1 WHERE V1.TASK_ID_ = T1.ID_")
                .count();
        log.info("count : {}", count);
    }


}
